<?php

namespace app\index\controller;

use think\Request;

class Index {
	// 静态数据，不可修改
	private $createPath = "/video/create";
	private $completePath = "/video/create/complete";
	private $searchPath = "/video/search";
	private $uploadFileTempPath = "F:/test_video/temp_video/";//文件上传到服务器的临时目录
	
	// 创建文件分片
	public function create(Request $request) {
		return \VodClient::execute ( json_encode ( $request->post () ), $this->createPath );
	}
	
	// 完成文件上传
	public function complete(Request $request) {
		return \VodClient::execute ( json_encode ( $request->post () ), $this->completePath );
	}
	
	// 查询文件
	public function search(Request $request) {
		return \VodClient::execute ( json_encode ( $request->post () ), $this->searchPath );
	}
		
	// 对文件进行分片上传 
	public function uploadFile(Request $request) {
		$uploadResult = array ();
		$segmentSize = 10 * 1024 * 1024; // 文件块大小：10MB
		
		// 获取请求参数
		$param = $request->post ();
		$regionCode = $param ["regionCode"];
		
		// 获取前端上传的文件
		$file = $request->file ( "video" );
		$fileInfo = $file->getInfo ();
		$fileSize = $fileInfo ["size"]; 
		$fName = $fileInfo ["name"];//文件名
		// 文件移动到服务器的临时目录，并且使用原文件名
		$info = $file->move ( $this->uploadFileTempPath, '' );
		if (!$info) {
			// 上传失败返回错误信息
			$uploadResult["code"] = "1";
			$uploadResult["message"] = $file->getError ();
			return $uploadResult;
		}
		// 注意：要用unset释放$info
		unset ( $info );
		$fileName = $this->uploadFileTempPath . $fName;
		
		// 构造“创建文件分片”请求
		$fileInfoParam = array (
			"mad5" => "",
			"fileSize" => $fileSize,
			"partSize" => $segmentSize 
		);
		$createPathReq = array (
			"regionCode" => $regionCode,
			"name" => $fName,
			"fileInfo" => json_encode ( $fileInfoParam ) 
		);
		// 执行“创建文件分片”请求
		$createPathResult = \VodClient::execute ( json_encode ( $createPathReq ), $this->createPath );
		$jsondata = json_decode($createPathResult);
		if($jsondata->code == "0") {
			$urlList = $jsondata->data->uploadUrls;
			$videoId = $jsondata->data->videoId;
			$segmentCount = count($urlList); //文件分片数等于uploadUrls的元素个数
			// 构造“完成文件上传”请求
			$completePathReq = array (
				"videoId" => $videoId,
				"etags" => []
			);
			// 以二进制（binary）方式打开要读取的文件
			$readFile = fopen ( $fileName, "rb" );
			$http = new \Http ();
			// 按照每个文件块的大小，顺序读取文件的内容
			for($i = 1; $i <= $segmentCount; $i ++) {
				$readSize = $segmentSize;
				if($i == $segmentCount) { // 如果是最后一个文件块，就算出最后一个文件块的大小
					$readSize = $fileSize - ($segmentCount - 1) * $segmentSize;
				}
				// 读取文件
				$contents = fread ( $readFile, $readSize );
				// 调用"文件上传"restful服务，并返回响应头
				$responseHeader = $http->doPutWithResponseHeader ( $urlList[$i-1], $contents, null );
				// 向etags对象数组添加数据
				$completePathReq["etags"][] = [
					"partNumber" => $i,
					"eTag" => self::resolveEtag($responseHeader)
				];
			}
			fclose ( $readFile );
			// 上传文件后要删除服务器上的文件
			unlink ($fileName); 

			// 执行“完成文件上传”请求
			$completePathResult = \VodClient::execute ( json_encode ( $completePathReq ), $this->completePath );
			$uploadResult = $completePathResult;
		}else {//返回错误
			$uploadResult = $createPathResult;
		}
		
		return $uploadResult; 
	}
	
	// 从响应头中解析出ETag的值
	function resolveEtag($responseHeader) {
		$etagHeaderName = "ETag:";
		$idx = strpos ( $responseHeader, $etagHeaderName );
		$end = strpos ( $responseHeader, "\r", $idx );
		$start = $idx + strlen ( $etagHeaderName );
		$eTag = substr ( $responseHeader, $start, $end - $start );
		$eTag = trim ( $eTag );
		$eTag = str_replace ( '"', '', $eTag );
		return $eTag;
	} 
	
	// 首页
	public function index() {
		return "这是首页";
	}
}
